﻿using Seagull.BarTender.Print;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Serialization.Formatters;
using System.Text;
using UniRlv.COL;
using UniRlv.Server.ILayer;
using UniRlv.Utility.AppLib;
using UniRlv.Utility.Extend;

namespace UniRlv.Utility
{
    public class WorkSpace
    {
        TcpChannel channel = null;
        List<ScannerDevice> scanners = new List<ScannerDevice>();
        List<PrintInfo> printerInfos;//打印信息
        List<List<string>> printDatas = new List<List<string>>();//打印数据
        DODevice doDev = null;
        public EventHandler<CodeSaveEventArg> CodeSaveEvent;
        public EventHandler<CodeScanEventArg> CodeScanEvent;//工控扫描枪触发
        public EventHandler<EventArgs> CodeRefreshEvent;//异常处理时触发
        public EventHandler<CodePrintEventArg> CodePrintEvent;//打印触发
        public EventHandler<EventArgs> TaskStartEvent;
        public EventHandler<EventArgs> TaskFinishEvent;
        public EventHandler<EventArgs> TaskResumeEvent;
        public EventHandler<EventArgs> TaskPauseEvent;

        int nMaunalScanner = 0;
        private string _errorString;
        public string ErrorString 
        {
            get
            {
                string buf = new string(_errorString.ToCharArray());
                _errorString = string.Empty;
                return buf;
            }
        }

        Engine engine = null; // The BarTender Print Engine

        public static WorkSpace GetInstance()
        {
            return Singleton<WorkSpace>.GetInstance();
        }

        public bool Init(string serverIP, ref string msg)
        {
            //客户端注册服务端事件
            try
            {
                BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();

                serverProvider.TypeFilterLevel = TypeFilterLevel.Full;

                IDictionary dict = new Hashtable();

                dict["port"] = 0;
                dict["name"] = "UniRlvChanel";
                dict["timeout"] = 30000;

                if (!string.IsNullOrEmpty(ConfigurationHelper.AppGetString("localIP")))
                {
                    dict["bindTo"] = ConfigurationHelper.AppGetString("localIP");
                }
                else//取最后一个ip
                {
                    dict["bindTo"] = NetHelper.GetLocalIp(true);
                }

                if (channel != null)
                {
                    ChannelServices.UnregisterChannel(channel);
                }

                PublicObject.BindingIP = dict["bindTo"].ToString();

                channel = new TcpChannel(dict,
                    new BinaryClientFormatterSinkProvider(), serverProvider);

                ChannelServices.RegisterChannel(channel, false);
                PublicObject.srv = (IServerOpr)(Activator.GetObject(typeof(IServerOpr),
                        string.Format("tcp://{0}:{1}/UniRlvSolu/UniRlv", serverIP, ConfigurationHelper.AppGetInt("port"))));

                PublicObject.arrCode1 = new MyList<CodeInfo>();
                PublicObject.arrCode2 = new List<CodeInfo>();
                PublicObject.arrCode3 = new List<CodeInfo>();
                PublicObject.arrCode4 = new List<CodeInfo>();
                PublicObject.arrCode1.bMergeOne = false;

                PublicObject.CodeScanned = new List<string>();
                PublicObject.CodeValid = new List<string>();
                PublicObject.CodeRlt = new List<CodeRltInfo>();

                List<CompanyInfo> li = DALOpr.QueryAll<CompanyInfo>(ref msg);

                if (li == null || li.Count == 0)
                {
                    //插入默认元素
                    CompanyInfo info = new CompanyInfo();
                    info.ID = DALOpr.GetNextObjectID("CompanyInfo");
                    info.name = "xxx公司";
                    info.userName = "xxx操作员";

                    msg = string.Empty;
                    if (DALOpr.Insert(info, ref msg))
                    {
                        PublicObject.CurCompany = info;
                    }
                    else
                    {
                        msg = "无法插入默认企业信息";
                        return false;
                    }
                }
                else
                {
                    //显示第一个元素
                    PublicObject.CurCompany = li[0];
                }

#region 数据库更新
                if (!DALOpr.IfColumnExist("PackageRule", "minTagGG"))
                {
                    msg = string.Empty;

                    if (!DALOpr.AddColumn("PackageRule", "minTagGG", "varchar(50) NULL", ref msg))
                    {
                        msg = "PackageRule表无法添加minTagGG列";
                        return false;
                    }
                }

                if (!DALOpr.IfColumnExist("ProductionTask", "minTagGG"))
                {
                    msg = string.Empty;

                    if (!DALOpr.AddColumn("ProductionTask", "minTagGG", "varchar(50) NULL", ref msg))
                    {
                        msg = "ProductionTask表无法添加minTagGG列";
                        return false;
                    }
                }
#endregion
                //初始化工控扫描枪
                List<LineDevice> infos = DALOpr.Query<LineDevice>("IO=" + (int)input_output.INPUT + " and deviceType=" + (int)in_device_type.IDT_MANUAL_SCANER, ref msg);

                if (infos.Count>0)
                {
                    ScannerDevice sd = new ScannerDevice(infos[0]);
                    sd.OnCode += sd_OnCode;

                    if (sd.Open())
                    {
                        scanners.Add(sd);
                        nMaunalScanner = 1;
                    }
                }

                CodePrcUtility.PRODUCT_CHECK = ConfigurationHelper.AppGetBoolean("checkProduct");
                CodePrcUtility.PRODUCT_CHECKLevel1 = ConfigurationHelper.AppGetBoolean("checkProductLevel1");
                CodePrcUtility.CODEREG = ConfigurationHelper.AppGetString("codeReg");
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return false;
            }

            return true;
        }

        public void Quit()
        {
            if (channel != null)
            {
                ChannelServices.UnregisterChannel(channel);
            }

            foreach (var item in scanners)
            {
                item.Close();
            }

            if (doDev!=null)
            {
                doDev.Close();
            }

            if (PublicObject.CurTask != null)
            {
                ProductionTask t = PublicObject.CurTask;
                t.state = (int)task_state.TS_STOP;
                string sql = EntityHelper.GetUpdateSql(PublicObject.CurTask);
                string msg = string.Empty;

                DALOpr.ExecuteNonQuery(sql, ref msg);

                //删除打印信息，回写未打印数据
                if (printerInfos != null)
                {
                    for (int i = 0; i < printerInfos.Count; i++)
                    {
                        File.WriteAllLines(printerInfos[i].CodePath, printDatas[i]);
                    }
                    printerInfos.Clear();
                    printDatas.Clear();
                }
            }
        }

        public bool RunTask()
        {
            //输入设备
            string msg = string.Empty;

            PublicObject.arrCode1.bMergeOne = false;
            PublicObject.bSecond = false;

            List<LineDevice> infos = DALOpr.Query<LineDevice>("stationNumber>0 and lineID=" + PublicObject.CurLine.ID, ref msg);

            ScannerDevice sd;
            bool bOK = true;



            foreach (var item in infos)
            {
                if (item.IO == (int)input_output.INPUT && (item.deviceType == (int)in_device_type.IDT_AUTO_SCANER
                    || item.deviceType == (int)in_device_type.IDT_OTHERS))
                {
                    sd = new ScannerDevice(item);
                    sd.OnCode += sd_OnCode;

                    bOK &= sd.Open();

                    if (!bOK)
                    {
                        _errorString = sd.ErrorString;
                        break;
                    }
                    else
                    {
                        scanners.Add(sd);

                        if (item.twiceScan == 1)
                        {
                            PublicObject.bSecond = true;
                        }

                        if (item.subDeviceNumber > 0 && item.stationNumber == 1)
                        {//1号工位有子设备，说明多台设备同时读取一级码
                            PublicObject.arrCode1.bMergeOne = true;
                        }
                    }
                }

                if (item.IO == (int)input_output.OUTPUT &&
                    (item.deviceType == (int)out_device_type.ODT_PLC
                    || item.deviceType == (int)out_device_type.ODT_RELAY
                    || item.deviceType == (int)out_device_type.ODT_OTHERS))
                {
                    doDev = new DODevice(item);
                    bOK &= doDev.Open();

                    if (!bOK)
                    {
                        _errorString = doDev.ErrorString;
                        break;
                    }
                }

                //综合扫描枪或功能扫描枪
                if (item.IO == (int)input_output.INPUT && (item.deviceType == (int)in_device_type.IDT_FUNC_SCANNER ||
                    item.deviceType == (int)in_device_type.IDT_UNI_SCANER))
                {

                    sd = new ScannerDevice(item);
                    sd.OnCode += sd_OnCode;

                    bOK &= sd.Open();

                    if (!bOK)
                    {
                        _errorString = sd.ErrorString;
                        break;
                    }
                    else
                    {
                        scanners.Add(sd);
                        CodePrcUtility.AddUniScanner(item);
                    }

                }

                //工控扫描枪
                if (item.IO == (int)input_output.INPUT && item.deviceType == (int)in_device_type.IDT_MANUAL_SCANER && nMaunalScanner == 0)
                {

                    sd = new ScannerDevice(item);
                    sd.OnCode += sd_OnCode;

                    bOK &= sd.Open();

                    if (!bOK)
                    {
                        _errorString = sd.ErrorString;
                        break;
                    }
                    else
                    {
                        scanners.Add(sd);
                        nMaunalScanner = 1;
                    }

                }

                //打印信息
                printerInfos = DALOpr.Query<PrintInfo>("taskID=" + PublicObject.CurTask.ID, ref msg);
                if (printerInfos!=null && printerInfos.Count>0)
                {
                    PublicObject.bPrint = true;

                    try
                    {
                        if (engine == null)
                        {
                            engine = new Engine(true);
                        }
                        
                    }
                    catch (Exception)
                    {
                    }

                    foreach (var pi in printerInfos)
                    {
                        if (!File.Exists(pi.CodePath))
                        {
                            bOK = false;
                            _errorString = "待打印数据文件不存在";
                            printDatas.Clear();
                            break;
                        }
                        else
                        {
                            List<string> datas = File.ReadAllLines(pi.CodePath).ToList();
                            printDatas.Add(datas);
                        }
                        
                    }
                    
                }
            }

            if (!bOK)
            {
                foreach (var item in scanners)
                {
                    item.Close();
                }
            }
            else
            {
                if (TaskStartEvent != null)
                {
                    TaskStartEvent(this, new EventArgs());
                }

                PublicObject.CurTask.state = (int)task_state.TS_RUN;
            }


            return bOK;
        }

        public void PauseTask()
        {
            foreach (var item in scanners)
            {
                if (item.Device.IO == (int)input_output.INPUT && item.Device.deviceType == (int)in_device_type.IDT_MANUAL_SCANER)
                {//工控扫描枪不暂停
                    continue;
                }
                item.Pause();
            }

            PublicObject.CurTask.state = (int)task_state.TS_PAUSE;

            if (TaskPauseEvent != null)
            {
                TaskPauseEvent(this, new EventArgs());
            }
        }

        public void ResumeTask()
        {
            foreach (var item in scanners)
            {
                if (item.Device.IO == (int)input_output.INPUT && item.Device.deviceType == (int)in_device_type.IDT_MANUAL_SCANER)
                {
                    continue;
                }

                item.Resume();
            }

            PublicObject.CurTask.state = (int)task_state.TS_RUN;

            if (TaskResumeEvent != null)
            {
                TaskResumeEvent(this, new EventArgs());
            }
        }

        public void ReStartTask()
        {
            //清除缓存数据
            PublicObject.arrCode1.Clear();
            PublicObject.arrCode2.Clear();
            PublicObject.arrCode3.Clear();
            PublicObject.arrCode4.Clear();

            PublicObject.CodeScanned.Clear();
            PublicObject.CodeValid.Clear();
            PublicObject.CodeRlt.Clear();

            PublicObject.Picks1 = 0;
            PublicObject.Picks2 = 0;
            PublicObject.Picks3 = 0;
            PublicObject.TopMan = 0;
            PublicObject.TopLoss = 0;

            if (TaskStartEvent!=null)
            {
                TaskStartEvent(this, new EventArgs());
            }
        }

        public void FinishTask(task_state ts, ref string strMsg)
        {
            //保存任务、码信息
            if (ts == task_state.TS_VERIFIED)
            {
                PublicObject.CurTask.scanQuantity = PublicObject.arrCode1.Count;
                PublicObject.CurTask.verifyer = PublicObject.CurUser.name;
                PublicObject.CurTask.packageState = (int)GetCurrentTaskPS();
            }


            PublicObject.CurTask.state = (int)ts;
            string sql = EntityHelper.GetUpdateSql(PublicObject.CurTask);
            string msg = string.Empty;

            DALOpr.ExecuteNonQuery(sql, ref msg);

            //设置为空任务，以启动下一任务
	        PublicObject.CurTask = null;

            PublicObject.arrCode1.Clear();
            PublicObject.arrCode2.Clear();
            PublicObject.arrCode3.Clear();
            PublicObject.arrCode4.Clear();

            PublicObject.CodeScanned.Clear();
            PublicObject.CodeValid.Clear();
            PublicObject.CodeRlt.Clear();

            PublicObject.Picks1 = 0;
            PublicObject.Picks2 = 0;
            PublicObject.Picks3 = 0;
            PublicObject.TopMan = 0;
            PublicObject.TopLoss = 0;

            for (int i = scanners.Count-1; i>=0; i--)
            {
                var item = scanners[i];

                if (item.Device.IO == (int)input_output.INPUT && item.Device.deviceType == (int)in_device_type.IDT_MANUAL_SCANER)
                {//工控扫描枪不关闭
                    continue;
                }

                item.Close();
                scanners.RemoveAt(i);
            }

            if (doDev!=null)
            {
                doDev.Close();
            }

	        //删除综合采集器
            CodePrcUtility.ClearUniScanner();

            if (TaskFinishEvent != null)
            {
                TaskFinishEvent(this, new EventArgs());
            }

            //删除打印信息，回写未打印数据
            if (printerInfos!=null)
            {
                for (int i = 0; i < printerInfos.Count; i++)
                {
                    File.WriteAllLines(printerInfos[i].CodePath, printDatas[i]);
                }
                printerInfos.Clear();
                printDatas.Clear();
            }          
        }

        public bool IfTaskFree()
        {
            if (PublicObject.CurTask != null && PublicObject.CurTask.state != (int)task_state.TS_NEW)
            {
                return false;
            }

            return true;
        }

        public void NotifyDataChanged()
        {
            if (CodeSaveEvent != null)
            {
                CodeSaveEvent(this, null);
            }
        }

        public void RefreshCodeQty()
        {
            if (CodeRefreshEvent != null)
            {
                CodeRefreshEvent(this, null);
            }
        }

        public package_state GetCurrentTaskPS()
        {
            if (CodePrcUtility.GetUnpackQty() > 0)
            {
                return package_state.PS_UNBOX;
            }

            if (CodePrcUtility.GetZeroQty() > 0)
            {
                return package_state.PS_ZERO;
            }

            return package_state.PS_NORMAL;
        }

        bool PrintOneLabel(PrintInfo pi, string code, ref string msg)
        {
            LabelFormatDocument lfd;

            lfd = engine.Documents.Open(pi.TemplatePath);

            try
            {
                lfd.SubStrings.SetSubString("code", code);
            }
            catch (Exception exp)
            {
                Console.WriteLine("写入Substring出现错误：" + exp.Message);
            }

            try
            {
                lfd.SubStrings.SetSubString("product", PublicObject.CurTask.tym);
            }
            catch (Exception exp)
            {
                Console.WriteLine("写入Substring出现错误：" + exp.Message);
            }

            try
            {
                lfd.SubStrings.SetSubString("pzwh", PublicObject.CurTask.pzwh);
            }
            catch (Exception exp)
            {
                Console.WriteLine("写入Substring出现错误：" + exp.Message);
            }

            try
            {
                lfd.SubStrings.SetSubString("specification", PublicObject.CurTask.gg);
            }
            catch (Exception exp)
            {
                Console.WriteLine("写入Substring出现错误：" + exp.Message);
            }

            try
            {
                lfd.SubStrings.SetSubString("batchNo", PublicObject.CurTask.batch);
            }
            catch (Exception exp)
            {
                Console.WriteLine("写入Substring出现错误：" + exp.Message);
            }

            try
            {
                lfd.SubStrings.SetSubString("produceDate", PublicObject.CurTask.produceDate.ToString("yyyy-MM-dd"));
            }
            catch (Exception exp)
            {
                Console.WriteLine("写入Substring出现错误：" + exp.Message);
            }

            try
            {
                lfd.SubStrings.SetSubString("yxq", PublicObject.CurTask.yxq.ToString("yyyy-MM-dd"));
            }
            catch (Exception exp)
            {
                Console.WriteLine("写入Substring出现错误：" + exp.Message);
            }

            try
            {
                Messages messages;
                lfd.PrintSetup.IdenticalCopiesOfLabel = pi.PrintQty;
                Result result = lfd.Print(PublicObject.CurTask.batch + "批次打印" + pi.StationNum + "级别码", out messages);//开始打印

                lfd.Close(SaveOptions.DoNotSaveChanges);

                msg = "";

                foreach (Seagull.BarTender.Print.Message message in messages)
                {
                    msg += "\n" + message.Text;
                }

                if (result == Result.Failure)
                {
                    if (!msg.Contains("Printer Maestro"))
                    {
                        return false;
                    }

                }

                return true;
            }
            catch (Exception exp)
            {
                msg = exp.Message;
                return false;
            }

        }

        void sd_OnCode(LineDevice dev, string code)
        {
            string msg = string.Empty;

            code = code.Trim();

            if (dev.IO == (int)input_output.INPUT && dev.deviceType == (int)in_device_type.IDT_MANUAL_SCANER)
            {
                if (CodeScanEvent != null)
                {
                    string bit24 = AppHelper.SYZSGet24BitFromCodeNoCheck(code);
                    CodeScanEvent(this, new CodeScanEventArg(dev, bit24, code));
                }

                return;
            }

            en_code_prc prc = CodePrcUtility.SaveCode(dev, code, ref msg);

            if (prc == en_code_prc.CP_NORMAL || prc == en_code_prc.CP_PRC_NORMAL)
            {
                if (dev.stationNumber == PublicObject.CurLine.stationQuantity && 
                    (dev.deviceType == (int)in_device_type.IDT_MANUAL_SCANER || dev.deviceType == (int)in_device_type.IDT_UNI_SCANER))
                {//顶级码并且手工扫描
                    PublicObject.TopMan++;
                }

                if (CodeSaveEvent!=null)
                {
                    if (prc == en_code_prc.CP_NORMAL)
                    {
                        CodeSaveEvent(this, new CodeSaveEventArg(dev, code, msg, true, prc));

                        //查询是否需要打印
                        if (PublicObject.bPrint)
                        {
                            foreach (var pi in printerInfos)
                            {
                                if (pi.StationNum == dev.stationNumber+1)
                                {
                                    int ratio;
                                    int idxPI = printerInfos.IndexOf(pi);
                                    msg = string.Empty;
                                    switch (pi.StationNum)
                                    {
                                        case 2:
                                            ratio = CodePrcUtility.GetCurLevelRatios()[PublicObject.CurTask.tagLevel - 2];
                                            if (PublicObject.arrCode1.Count%ratio == 0 && PublicObject.arrCode1.Count>0)
                                            {//满整包装
                                                if (PrintOneLabel(pi, printDatas[idxPI][0], ref msg) && CodePrcUtility.SavePrintCode(printDatas[idxPI][0], 2, ref msg) == en_code_prc.CP_NORMAL)
                                                {
                                                    PublicObject.CodeScanned.Add(printDatas[idxPI][0]);
                                                    printDatas[idxPI].RemoveAt(0);

                                                    if (CodePrintEvent!=null)
                                                    {
                                                        CodePrintEvent(this, new CodePrintEventArg(pi, printDatas[idxPI][0], "打印成功"));
                                                    }

                                                }
                                                else
                                                {
                                                    if (CodePrintEvent != null)
                                                    {
                                                        CodePrintEvent(this, new CodePrintEventArg(pi, printDatas[idxPI][0], msg));
                                                    }
                                                }
                                            }

                                            break;
                                        case 3:
                                            ratio = CodePrcUtility.GetCurLevelRatios()[PublicObject.CurTask.tagLevel - 3];

                                            if (PublicObject.bSecond)
                                            {//二次扫描
                                                if (dev.twiceScan == 1)
                                                {
                                                    if (CodePrcUtility.GetScanTwiceQty() % ratio == 0 && CodePrcUtility.GetScanTwiceQty()>0 && CodePrcUtility.GetScanTwiceQty()>PublicObject.arrCode3.Count*ratio)
                                                    {//满整包装并且尚未打印，二次采集可能或重复采集
                                                        if (PrintOneLabel(pi, printDatas[idxPI][0], ref msg) && CodePrcUtility.SavePrintCode(printDatas[idxPI][0], 3, ref msg) == en_code_prc.CP_NORMAL)
                                                        {
                                                            PublicObject.CodeScanned.Add(printDatas[idxPI][0]);
                                                            printDatas[idxPI].RemoveAt(0);

                                                            if (CodePrintEvent != null)
                                                            {
                                                                CodePrintEvent(this, new CodePrintEventArg(pi, printDatas[idxPI][0], "打印成功"));
                                                            }

                                                            //判断是否需要打印四级码
                                                            for (int i = 0; i < printerInfos.Count; i++)
                                                            {
                                                                if (printerInfos[i].StationNum == 4)
                                                                {//四级码也需要打印
                                                                    ratio = CodePrcUtility.GetCurLevelRatios()[PublicObject.CurTask.tagLevel - 4];
                                                                    if (PublicObject.arrCode3.Count % ratio == 0 && PublicObject.arrCode3.Count > 0)
                                                                    {//满整包装
                                                                        if (PrintOneLabel(printerInfos[i], printDatas[i][0], ref msg) && CodePrcUtility.SavePrintCode(printDatas[i][0], 4, ref msg) == en_code_prc.CP_NORMAL)
                                                                        {
                                                                            PublicObject.CodeScanned.Add(printDatas[i][0]);
                                                                            printDatas[i].RemoveAt(0);

                                                                            if (CodePrintEvent != null)
                                                                            {
                                                                                CodePrintEvent(this, new CodePrintEventArg(printerInfos[i], printDatas[i][0], "打印成功"));
                                                                            }

                                                                            break;
                                                                        }
                                                                        else
                                                                        {
                                                                            if (CodePrintEvent != null)
                                                                            {
                                                                                CodePrintEvent(this, new CodePrintEventArg(printerInfos[i], printDatas[i][0], msg));
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            if (CodePrintEvent != null)
                                                            {
                                                                CodePrintEvent(this, new CodePrintEventArg(pi, printDatas[idxPI][0], msg));
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                
                                                if (PublicObject.arrCode2.Count % ratio == 0 && PublicObject.arrCode2.Count>0)
                                                {//满整包装
                                                    if (PrintOneLabel(pi, printDatas[idxPI][0], ref msg) && CodePrcUtility.SavePrintCode(printDatas[idxPI][0], 3, ref msg) == en_code_prc.CP_NORMAL)
                                                    {
                                                        PublicObject.CodeScanned.Add(printDatas[idxPI][0]);
                                                        printDatas[idxPI].RemoveAt(0);

                                                        if (CodePrintEvent != null)
                                                        {
                                                            CodePrintEvent(this, new CodePrintEventArg(pi, printDatas[idxPI][0], "打印成功"));
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (CodePrintEvent != null)
                                                        {
                                                            CodePrintEvent(this, new CodePrintEventArg(pi, printDatas[idxPI][0], msg));
                                                        }
                                                    }
                                                }

                                            }
                                            break;
                                        case 4:
                                            ratio = CodePrcUtility.GetCurLevelRatios()[PublicObject.CurTask.tagLevel - 4];
                                            if (PublicObject.arrCode3.Count % ratio == 0 && PublicObject.arrCode3.Count>0)
                                            {//满整包装
                                                if (PrintOneLabel(pi, printDatas[idxPI][0], ref msg) && CodePrcUtility.SavePrintCode(printDatas[idxPI][0], 4, ref msg) == en_code_prc.CP_NORMAL)
                                                {
                                                    PublicObject.CodeScanned.Add(printDatas[idxPI][0]);
                                                    printDatas[idxPI].RemoveAt(0);

                                                    if (CodePrintEvent != null)
                                                    {
                                                        CodePrintEvent(this, new CodePrintEventArg(pi, printDatas[idxPI][0], "打印成功"));
                                                    }
                                                }
                                                else
                                                {
                                                    if (CodePrintEvent != null)
                                                    {
                                                        CodePrintEvent(this, new CodePrintEventArg(pi, printDatas[idxPI][0], msg));
                                                    }
                                                }
                                            }
                                            break;
                                    default:
                                            break;
                                    }

                                }
                            }
                        }
                        
                    }
                    else
                    {
                        CodeSaveEvent(this, new CodeSaveEventArg(dev, code, msg, true, prc));
                    }

                }
            }
            else if (prc == en_code_prc.CP_STEPS)
            {//手持扫码处理过程
                if (CodeSaveEvent != null)
                {
                    CodeSaveEvent(this, new CodeSaveEventArg(dev, code, msg, false, prc));
                }
            }
            else//错误处理
            {
					
                if (prc==en_code_prc.CP_PICK && dev.autoPick==1 && dev.stationNumber==1)
				{//一级码自动剔除，无须发命令
					Console.WriteLine("Pick1\n");
                    PublicObject.Picks1++;
                    CodeSaveEvent(this, new CodeSaveEventArg(dev, code, msg, false, prc));
					return;//一级码的解码失败可以直接返回继续处理，采集器自动
				}

                if (dev.stationNumber == 1)
                {
                    if (doDev != null)
                        doDev.Pick(dev.stationNumber, null);

                    if (dev.deviceType == (int)in_device_type.IDT_OTHERS)
                    {
                        foreach (var item in scanners)
                        {
                            if (item.Device.Equals(dev))
                            {
                                item.Send("P");
                            }
                        }
                    }
                }

                if (dev.alarm == 1)
                {
                    if (doDev != null)
                        doDev.Alarm(dev.stationNumber, null);

                    if (dev.deviceType == (int)in_device_type.IDT_OTHERS)
                    {
                        foreach (var item in scanners)
                        {
                            if (item.Device.Equals(dev))
                            {
                                item.Send("A");
                            }
                        }
                    }
                }


                    //二级以上自动剔除，需要删除低级别码
                    //if (dev.stationNumber==2 && dev.twiceScan == 0)
                    //{//删除对应低级码
                    //    Console.WriteLine("Pick2\n");
                    //    CodePrcUtility.PickTopPackage21(ref msg);
                    //}

                    //if (dev.stationNumber == 3)
                    //{//删除对应低级码
                    //    //CodePrcUtility.PickTopPackage31(ref msg);
                    //}


                if (prc == en_code_prc.CP_PICK)
                {
                    switch (dev.stationNumber)
                    {
                        case 1:
                            PublicObject.Picks1++;
                            break;
                        case 2:
                            PublicObject.Picks2++;
                            break;
                        case 3:
                            PublicObject.Picks3++;
                            break;
                        default:
                            break;
                    }

                    if (dev.stationNumber == PublicObject.CurLine.stationQuantity)
                    {//顶级码
                        PublicObject.TopLoss++;
                    }
                }

                if (CodeSaveEvent != null)
                {
                    CodeSaveEvent(this, new CodeSaveEventArg(dev, code, msg, false, prc));
                }
                
            }
        }
    }
}
